<template>
  <div class="schedule-detail-container">
    <el-page-header @back="$router.go(-1)" content="排期详情" />
    
    <el-card v-loading="loading" class="detail-card">
      <el-descriptions title="排期基本信息" :column="2" border>
        <el-descriptions-item label="排期ID">{{ scheduleData.id }}</el-descriptions-item>
        <el-descriptions-item label="状态">
          <el-tag :type="getStatusType(scheduleData.status)">
            {{ statusMap[scheduleData.status] || scheduleData.status }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="广告标题">{{ scheduleData.advertisementTitle }}</el-descriptions-item>
        <el-descriptions-item label="设备名称">{{ scheduleData.deviceName }}</el-descriptions-item>
        <el-descriptions-item label="开始投放时间">{{ formatTime(scheduleData.startTime) }}</el-descriptions-item>
        <el-descriptions-item label="结束投放时间">{{ formatTime(scheduleData.endTime) }}</el-descriptions-item>
        <el-descriptions-item label="创建时间">{{ formatTime(scheduleData.createdTime) }}</el-descriptions-item>
        <el-descriptions-item label="更新时间">{{ formatTime(scheduleData.updatedTime) }}</el-descriptions-item>
      </el-descriptions>
      
      <div class="section">
        <h3>播放时段</h3>
        <div v-if="scheduleData.timeSlots && scheduleData.timeSlots.length > 0" class="time-slots">
          <el-tag 
            v-for="(slot, index) in scheduleData.timeSlots" 
            :key="index"
            size="large"
            class="time-slot-tag"
          >
            {{ slot.startTime }} - {{ slot.endTime }}
          </el-tag>
        </div>
        <el-empty v-else description="全天播放" />
      </div>
      
      <div class="section">
        <h3>效果数据</h3>
        <el-row :gutter="20">
          <el-col :span="8">
            <el-statistic title="展示次数" :value="scheduleData.impressions || 0">
              <template #suffix>
                <span>次</span>
              </template>
            </el-statistic>
          </el-col>
          <el-col :span="8">
            <el-statistic title="点击次数" :value="scheduleData.clicks || 0">
              <template #suffix>
                <span>次</span>
              </template>
            </el-statistic>
          </el-col>
          <el-col :span="8">
            <el-statistic 
              title="点击率" 
              :value="calculateCTR(scheduleData.impressions, scheduleData.clicks)" 
              :precision="2"
            >
              <template #suffix>
                <span>%</span>
              </template>
            </el-statistic>
          </el-col>
        </el-row>
      </div>
      
      <div class="action-btns">
        <el-button @click="$router.go(-1)">返回</el-button>
        <el-button 
          v-if="canCancel" 
          type="danger" 
          @click="handleCancel"
        >
          取消排期
        </el-button>
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessageBox, ElMessage } from 'element-plus'
import { getScheduleDetail, cancelSchedule } from '@/api/schedule'
import dayjs from 'dayjs'

const route = useRoute()
const router = useRouter()
const loading = ref(false)
const scheduleData = ref({
  id: null,
  advertisementId: null,
  advertisementTitle: '',
  deviceId: null,
  deviceName: '',
  startTime: null,
  endTime: null,
  timeSlots: [],
  status: '',
  createdTime: null,
  updatedTime: null,
  impressions: 0,
  clicks: 0
})

// 状态映射
const statusMap = {
  'PENDING': '待执行',
  'RUNNING': '执行中',
  'COMPLETED': '已完成',
  'CANCELLED': '已取消'
}

// 是否可以取消排期
const canCancel = computed(() => {
  return ['PENDING', 'RUNNING'].includes(scheduleData.value.status)
})

// 获取排期详情
const fetchScheduleDetail = async () => {
  try {
    loading.value = true
    const res = await getScheduleDetail(route.params.id)
    
    if (res.data.code === 200) {
      scheduleData.value = res.data.data
    } else {
      ElMessage.error(res.data.message || '获取排期详情失败')
    }
  } catch (error) {
    console.error('获取排期详情失败:', error)
    ElMessage.error('获取排期详情失败')
  } finally {
    loading.value = false
  }
}

// 处理取消排期
const handleCancel = async () => {
  try {
    await ElMessageBox.confirm(
      `确定要取消排期 #${scheduleData.value.id} (${scheduleData.value.advertisementTitle} - ${scheduleData.value.deviceName}) 吗？`,
      '取消排期',
      {
        confirmButtonText: '确认取消',
        cancelButtonText: '返回',
        type: 'warning'
      }
    )
    
    const res = await cancelSchedule(scheduleData.value.id)
    
    if (res.data.code === 200) {
      ElMessage.success('排期已成功取消')
      // 刷新详情
      fetchScheduleDetail()
    } else {
      ElMessage.error(res.data.message || '取消排期失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('取消排期失败:', error)
      ElMessage.error('取消排期失败')
    }
  }
}

// 计算点击率
const calculateCTR = (impressions, clicks) => {
  if (!impressions || impressions === 0) return 0
  return (clicks / impressions) * 100
}

// 获取状态类型
const getStatusType = (status) => {
  const typeMap = {
    'PENDING': 'info',
    'RUNNING': 'primary',
    'COMPLETED': 'success',
    'CANCELLED': 'danger'
  }
  return typeMap[status] || 'info'
}

// 时间格式化
const formatTime = (time) => {
  return time ? dayjs(time).format('YYYY-MM-DD HH:mm:ss') : '--'
}

onMounted(() => {
  fetchScheduleDetail()
})
</script>

<style scoped>
.schedule-detail-container {
  padding: 20px;
}

.detail-card {
  margin-top: 20px;
}

.section {
  margin-top: 30px;
}

.time-slots {
  margin-top: 10px;
}

.time-slot-tag {
  margin-right: 10px;
  margin-bottom: 10px;
}

.action-btns {
  margin-top: 30px;
  display: flex;
  justify-content: flex-end;
}
</style>